<template>
  <div class="app-container">
    <div class="volume-header">
      <div class="volume-title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/novel/project' }">小说项目</el-breadcrumb-item>
          <el-breadcrumb-item>{{ currentProject?.title || '加载中...' }}</el-breadcrumb-item>
          <el-breadcrumb-item>卷册管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="volume-actions">
        <el-button-group>
          <el-button type="success" @click="handleNextStep" :disabled="!canGoNext" size="small">
            <el-icon><Right /></el-icon> 下一步
          </el-button>
          <el-button type="primary" @click="handleBatchSave" :disabled="!volumes.length" size="small">
            <el-icon><DocumentAdd /></el-icon> 保存所有卷册
          </el-button>
          <el-button type="warning" @click="handleAddVolume" size="small">
            <el-icon><Plus /></el-icon> 手动添加卷册
          </el-button>
        </el-button-group>
      </div>
    </div>

    <el-row :gutter="24" class="volume-page">
      <!-- 左侧AI对话区域 -->
      <el-col :span="9" class="left-panel">
        <div class="panel-container">
          <div class="panel-header">
            <div class="header-icon">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="header-title">AI分卷助手</div>
            <el-tag effect="plain" type="info" size="small">智能规划</el-tag>
          </div>
          <div class="panel-body">
            <NovelAiChat
              ref="aiChatRef"
              title="AI分卷助手"
              placeholder="请描述您想要的分卷结构，例如：'请根据主线剧情，生成5个分卷，每个分卷包含名称和简介'"
              :loading="aiLoading"
              :enable-context="enableContext"
              @send="handleAiChat"
              @context-change="handleContextChange"
              @abort="handleAbortAI"
            />
          </div>
        </div>
      </el-col>

      <!-- 右侧卷册列表 -->
      <el-col :span="15" class="right-panel">
        <div class="panel-container">
          <div class="panel-header">
            <div class="header-title">
              <el-icon><Collection /></el-icon> 卷册列表
              <el-badge :value="volumes.length" class="volume-badge" :hidden="!volumes.length" />
            </div>
            <div class="header-actions">
              <el-tooltip content="批量删除" placement="top">
                <el-button type="danger" :disabled="!selectedVolumes.length" @click="handleBatchDelete" size="small" circle>
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="刷新列表" placement="top">
                <el-button type="info" @click="getList" plain size="small" circle>
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>

          <div class="panel-body">
            <div v-if="isSummaryLoading" class="ai-loading-overlay">
              <div class="loading-content">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>AI正在生成卷册数据...</span>
              </div>
            </div>

            <el-table
              v-loading="loading"
              :data="volumes"
              @selection-change="handleSelectionChange"
              border
              stripe
              size="large"
              class="volume-table"
              :header-cell-style="{ background: '#f5f7fa' }"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="序号" type="index" width="60" align="center" />
              <el-table-column label="分卷名称" min-width="180">
                <template #default="{ row }">
                  <el-input
                    v-model="row.title"
                    placeholder="请输入分卷名称"
                    clearable
                  />
                </template>
              </el-table-column>
              <el-table-column label="分卷简介" min-width="300">
                <template #default="{ row }">
                  <el-input
                    v-model="row.description"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入分卷简介"
                    resize="none"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                <template #default="{ $index }">
                  <div class="volume-actions">
                    <el-button type="danger" link @click="handleDelete($index)">
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="volume-tips" v-if="!volumes.length && !loading && !isSummaryLoading">
              <el-empty description="请在左侧与AI对话，生成分卷信息" :image-size="120">
                <template #extra>
                  <el-button type="primary" @click="handleAddVolume" size="small">
                    <el-icon><Plus /></el-icon> 手动添加卷册
                  </el-button>
                </template>
              </el-empty>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getVolume, addVolume, updateVolume, listVolume, delVolume } from "@/api/novel/volume"
import { getProject } from '@/api/novel/project'
import NovelAiChat from '@/components/NovelAiChat/index.vue'
import { useAIStream, PlatformType, AIModelType } from "@/components/Hook/useStreamFetch"
import {
  Right, Plus, Delete, Refresh, DocumentAdd,
  Collection, ChatDotRound, Loading
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 项目数据
const currentProject = ref(null)
const loading = ref(false)
const saveLoading = ref(false)
const currentVolume = ref(null)
const volumes = ref([])
const selectedVolumes = ref([])

// 表单参数
const form = ref({
  id: undefined,
  projectId: undefined,
  title: '',
  summary: ''
})

const rules = ref({
  title: [
    { required: true, message: '分卷名称不能为空', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '分卷简介不能为空', trigger: 'blur' }
  ]
})

// 表单引用
const volumeFormRef = ref(null)

// 计算属性
const canGoNext = computed(() => {
  return currentProject.value && volumes.value.length > 0
})

// AI对话相关
const aiLoading = ref(false)
const aiChatRef = ref(null)
const enableContext = ref(true)

// 创建 AI 对话实例
const summaryHook = useAIStream({
  platform: PlatformType.VOLCANO,
  authToken: 'f9c1148b-26fc-4c92-8977-fca871de1af3',
  model: AIModelType.DEEPSEEK,
  enableContext: true,
  maxContextMessages: 10
})

const {
  data: summaryData,
  isLoading: isSummaryLoading,
  error: summaryError,
  chat: startAiChat,
  abortFetch: abortSummary,
  lastMessage
} = summaryHook

// 记录上一次解析的文本长度
let lastParsedLength = 0;

// 监听AI响应数据，进行实时解析和显示
watch(summaryData, (newVal) => {
  if (newVal) {
    // 更新AI对话内容 - 流式显示
    aiChatRef.value?.addAiResponse({ isStreaming: true, content: newVal })

    // 实时解析分卷信息
    if (newVal.length > lastParsedLength) {
      parseVolumeData(newVal);
      lastParsedLength = newVal.length;
    }
  }
})

// 监听AI加载状态
watch(isSummaryLoading, (isLoading) => {
  aiLoading.value = isLoading
  if (!isLoading && lastMessage.value) {
    // 流程结束时进行最后的完整解析
    parseVolumeData(lastMessage.value, true);
    // 结束流式显示
    aiChatRef.value?.addAiResponse({ isStreaming: true, end: true })
    // 重置解析长度
    lastParsedLength = 0;
  }
})

// 获取项目信息
const getProjectInfo = async () => {
  const projectId = route.query.projectId
  if (!projectId) {
    ElMessage.warning('请先选择小说项目')
    router.push('/novel/project')
    return
  }

  try {
    const response = await getProject(projectId.toString())
    currentProject.value = response.data
    form.value.projectId = projectId.toString()
    getList()
  } catch (error) {
    console.error('获取项目信息失败:', error)
    ElMessage.error('获取项目信息失败')
  }
}

// 获取分卷列表
const getList = async () => {
  loading.value = true
  try {
    const response = await listVolume({
      projectId: currentProject.value.id.toString()
    })
    volumes.value = response.rows.map(item => ({
      id: item.id,
      title: item.title,
      description: item.summary,
      orderIndex: item.orderIndex
    }))
  } catch (error) {
    console.error('获取分卷列表失败:', error)
    ElMessage.error('获取分卷列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分卷点击
const handleVolumeClick = (row) => {
  currentVolume.value = row
  form.value = {
    id: row.id ? String(row.id) : undefined,
    projectId: row.projectId ? String(row.projectId) : undefined,
    title: row.title,
    summary: row.summary
  }
}

// 处理添加分卷
const handleAddVolume = () => {
  currentVolume.value = null
  form.value = {
    id: undefined,
    projectId: currentProject.value.id ? String(currentProject.value.id) : undefined,
    title: '',
    summary: ''
  }
}

// 处理编辑分卷
const handleEditVolume = (row) => {
  handleVolumeClick(row)
}

// 处理删除分卷
const handleDelete = (index) => {
  volumes.value.splice(index, 1)
  // 更新序号
  volumes.value.forEach((volume, idx) => {
    volume.orderIndex = idx + 1
  })
}

// 处理保存
const handleSave = async () => {
  if (!volumeFormRef.value) return

  try {
    await volumeFormRef.value.validate()
    saveLoading.value = true

    const submitData = {
      ...form.value,
      projectId: currentProject.value.id
    }

    if (currentVolume.value) {
      await updateVolume(submitData)
      ElMessage.success('修改成功')
    } else {
      await addVolume(submitData)
      ElMessage.success('保存成功')
    }

    getList()
  } catch (error) {
    console.error('保存分卷失败:', error)
    ElMessage.error('保存分卷失败')
  } finally {
    saveLoading.value = false
  }
}

// 处理下一步
const handleNextStep = () => {
  router.push({
    path: '/novel/chapterOutline',
    query: { projectId: currentProject.value.id }
  })
}

// 处理终止AI对话
const handleAbortAI = () => {
  abortSummary()
  aiLoading.value = false
  // 结束流式显示
  aiChatRef.value?.addAiResponse({ isStreaming: true, end: true })
}

// 解析卷册数据的函数
const parseVolumeData = (content, isFinal = false) => {
  try {
    const lines = content.split('\n')
    let currentVolume = { title: '', description: '' }
    let isCollectingVolume = false
    let tempVolumes = [] // 临时存储完整的分卷信息

    for (const line of lines) {
      // 检查是否开始新的分卷
      if (line.includes('分卷名称：')) {
        // 如果已经在收集分卷信息，先保存当前分卷
        if (isCollectingVolume && currentVolume.title && currentVolume.description) {
          tempVolumes.push({
            ...currentVolume,
            orderIndex: tempVolumes.length + 1
          })
        }

        // 开始收集新的分卷信息
        isCollectingVolume = true
        currentVolume = {
          title: line.split('：')[1]?.trim() || '',
          description: ''
        }
      }
      // 检查是否是分卷简介
      else if (line.includes('分卷简介：') && isCollectingVolume) {
        currentVolume.description = line.split('：')[1]?.trim() || '';
      }
      // 如果遇到空行且正在收集分卷信息，保存当前分卷
      else if (line.trim() === '' && isCollectingVolume && currentVolume.title && currentVolume.description) {
        tempVolumes.push({
          ...currentVolume,
          orderIndex: tempVolumes.length + 1
        })
        isCollectingVolume = false
        currentVolume = { title: '', description: '' }
      }
      // 如果正在收集简介，追加内容
      else if (isCollectingVolume && currentVolume.title && line.trim() !== '') {
        if (currentVolume.description) {
          currentVolume.description += '\n' + line.trim();
        } else {
          currentVolume.description = line.trim();
        }
      }
    }

    // 处理最后一个分卷
    if (isCollectingVolume && currentVolume.title && currentVolume.description) {
      tempVolumes.push({
        ...currentVolume,
        orderIndex: tempVolumes.length + 1
      })
    }

    // 只有在最终解析或者有完整卷册时才更新
    if (tempVolumes.length > 0 && (isFinal || tempVolumes.every(v => v.title && v.description))) {
      volumes.value = tempVolumes;
      if (isFinal) {
        ElMessage.success(`成功生成 ${tempVolumes.length} 个分卷`);
      }
    }
  } catch (error) {
    console.error('解析AI响应失败:', error);
  }
}

// 处理AI对话
const handleAiChat = async (data) => {
  try {
    const { message, context } = data

    const systemPrompt = `你是一个专业的小说分卷设计助手。请根据用户的需求，生成合适的分卷设定。
要求：
1. 每个分卷必须包含名称和简介
2. 分卷名称要简洁有力，能体现该卷的核心内容
3. 分卷简介要详细描述该卷的主要情节和发展
4. 分卷之间要有连贯性，体现故事的发展脉络
5. 请严格按照以下格式输出每个分卷：
---
分卷名称：xxx
分卷简介：xxx
---

注意：
- 每个分卷之间用空行分隔
- 分卷名称和简介要清晰明确
- 确保每个分卷的信息完整
- 请一次完整输出所有分卷信息`

    // 开始流式显示
    aiChatRef.value?.addAiResponse({ isStreaming: true, start: true })

    // 重置解析长度
    lastParsedLength = 0;

    // 使用优化后的AI聊天函数
    await startAiChat(message, systemPrompt)

  } catch (error) {
    console.error('AI生成失败:', error)
    ElMessage.error('AI生成失败，请重试')
    // 结束流式显示
    aiChatRef.value?.addAiResponse({ isStreaming: true, end: true })
  } finally {
    aiLoading.value = false
  }
}

// 处理上下文变化
const handleContextChange = (value) => {
  if (!value) {
    // 当禁用上下文时，提示用户
    ElMessageBox.confirm(
      '禁用上下文后，AI将无法看到之前的对话历史。确定要禁用吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      // 用户确认后，清空对话历史
      aiChatRef.value?.clearHistory()
      enableContext.value = false
      ElMessage.success('已禁用上下文，对话历史已清空')
    }).catch(() => {
      // 用户取消，保持上下文启用状态
      enableContext.value = true
    })
  } else {
    enableContext.value = true
    ElMessage.success('已启用上下文，AI可以看到之前的对话历史')
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedVolumes.value = selection
}

// 处理批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    '确定要删除选中的分卷吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const selectedIndexes = selectedVolumes.value.map(volume =>
      volumes.value.findIndex(v => v === volume)
    ).sort((a, b) => b - a)

    selectedIndexes.forEach(index => {
      volumes.value.splice(index, 1)
    })

    // 更新序号
    volumes.value.forEach((volume, idx) => {
      volume.orderIndex = idx + 1
    })

    ElMessage.success('删除成功')
  })
}

// 处理批量保存
const handleBatchSave = async () => {
  try {
    loading.value = true
    const promises = volumes.value.map(volume => {
      const data = {
        projectId: currentProject.value.id,
        title: volume.title,
        description: volume.description,
        orderIndex: volume.orderIndex
      }

      if (volume.id) {
        return updateVolume({ ...data, id: volume.id })
      } else {
        return addVolume(data)
      }
    })

    await Promise.all(promises)
    ElMessage.success('保存成功')
    getList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getProjectInfo()
})
</script>

<style lang="scss" scoped>
.volume-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.volume-page {
  height: calc(100vh - 160px);

  .left-panel, .right-panel {
    height: 100%;
  }

  .panel-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100%;
    border: 1px solid #ebeef5;

    .panel-header {
      padding: 16px;
      border-bottom: 1px solid #ebeef5;
      background: linear-gradient(to right, #f8f9fb, #ffffff);
      display: flex;
      align-items: center;
      gap: 10px;

      .header-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 28px;
        height: 28px;
        border-radius: 50%;
        background: #409EFF;
        color: white;
      }

      .header-title {
        flex: 1;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .header-actions {
        display: flex;
        gap: 8px;
      }
    }

    .panel-body {
      flex: 1;
      padding: 0;
      overflow: hidden;
      position: relative;

      .ai-loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        z-index: 10;
        display: flex;
        align-items: center;
        justify-content: center;

        .loading-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 16px;

          .el-icon {
            font-size: 32px;
            color: #409EFF;
          }

          span {
            font-size: 16px;
            color: #606266;
          }
        }
      }

      .volume-table {
        height: 100%;

        :deep(.el-table__inner-wrapper) {
          height: 100%;
        }

        :deep(.el-table__body-wrapper) {
          overflow-y: auto;
        }
      }

      .volume-tips {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.volume-badge {
  margin-left: 8px;
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.panel-container {
  animation: fadeIn 0.3s ease-out;
}
</style>
